import gen.YYParser;
import bison.LexToken;
import bison.LexerBase;

class MyLexer extends LexerBase, implements Lexer
{
   var functions:Hash<Float->Float>;

   public function new(inString:String, inFilename:String="")
   {
      super(inString,inFilename);
      consumeNewline = false;
      tokInt = YYParser.NUM;
      tokFloat = YYParser.NUM;

      functions = new Hash<Float->Float>();
      functions.set("cos",Math.cos);
      functions.set("sin",Math.sin);
      functions.set("tan",Math.tan);
      functions.set("sqrt",Math.sqrt);
      functions.set("abs",Math.abs);
   }

   public function parseInput(inParser:YYParser, inInput:String) : Bool
   {
      setString(inInput,fileName);
      while(true)
      {
         var tok = yylex();
         if (tok==0)
            return true;
         var result = inParser.parseToken(tok, getLVal(),new Location(getStartPos(),getEndPos()) );
         if (result==YYParser.PARSE_FAIL)
            return false;
         else if (result==YYParser.PARSE_COMPLETE)
            return true;
      }
      return false;
   }

   override function onLexerError(message:String) : Int
   {
      lvalue = message;
      return YYParser.ERROR;
   }

   override function processIdent(name:String) : Int
   {
      if (functions.exists(name))
      {
         lvalue = functions.get(name);
         return YYParser.FNCT;
      }
      if (name=="quit")
         return YYParser.YYACCEPT;
      lvalue = name;
      return YYParser.VAR;
   }
}


